<?php

namespace AdminModule\Models;

/**
 * Image
 *
 * @author David
 */
class Image extends \Nette\Database\Table\Selection {

    /**
     *
     * @var \AdminModule\Models\ImageConfig 
     */
    private $config;
    
    private $filter = array('type', 'name', 'title', 'description', 'order', 'main');

    /**
     * 
     * @param \Nette\Database\Connection $connection
     */
    public function __construct(\Nette\Database\Connection $connection) {
        $this->config = new \AdminModule\Models\ImageConfig($connection);
        parent::__construct('images', $connection);
    }
    
    public function filter($data) {
        return \array_intersect_key($data, \array_flip($this->filter));
    }
    
    public function getShowroomImages(\Nette\Database\Table\ActiveRow $showroom) {
        $ids = $this->query("SELECT id_image FROM showroom_has_images WHERE id_showroom = " . $showroom->id_showroom)
                ->execute()->fetchAll(\PDO::FETCH_COLUMN);
        if (\count($ids) > 0) {
            return $this->where("id_image IN (" . implode(',', array_values($ids)) . ")");
        }
        return array();
    }

    /**
     * 
     * @param array $data
     * @throws \LogicException
     */
    public function insert($data) {
        if (!isset($data['image'])) {
            throw new \LogicException('Soubor obrázku není nastaven');
        }
        $uploadedImage = $data['image'];
        if (!$this->checkFile($uploadedImage)) {
            throw new \LogicException('Soubor s obrázkem se nepodařilo načíst nebo je v nepodporovaném formátu');
        }
        $imageName = $this->getUniqueImageName($uploadedImage->getSanitizedName());
        $data['name'] = $imageName;
        $imageFile = new \AdminModule\Helpers\Image($imageName, $data['type'], $this->config);
        $imageFile->save($uploadedImage->getTemporaryFile());
        return parent::insert($this->filter($data));
    }

    /**
     * 
     * @param array $data
     * @throws 
     */
    public function update($data) {
        $image = $this->getCurrentImage($data);
        if (isset($data['image']) && $data['image']->isImage()) {
            $data['name'] = $this->replaceImageFile($data['image'], $data['type'], $image);
        }
        
        $image->update($this->filter($data));
        return $image;
    }
    
    /**
     * Smazani souboru obrazku.
     * 
     * @param \Nette\Database\Table\ActiveRow $image
     */
    public function deleteImageFile(\Nette\Database\Table\ActiveRow $image) {
        $imageFile = new \AdminModule\Helpers\Image($image->name, $image->type, $this->config);
        $imageFile->delete();
    }
    
    /**
     * Smazani db objektu obrazku i jeho souboru podle id obrazku.
     * 
     * @param int $idImage
     */
    public function deleteWithFileByImageId($idImage) {        
        $imageForDelete = $this->get($idImage);
        $this->deleteImageFile($imageForDelete);
        $imageForDelete->delete();
    }

    /**
     * 
     * @param \AdminModule\Models\Nette\Http\FileUpload $uploadedFile
     * @param string $type
     * @param string $image
     * @return string
     * @throws \LogicException
     */
    private function replaceImageFile(\Nette\Http\FileUpload $uploadedFile, $type, $oldImage) {
        if (!$this->checkFile($uploadedFile)) {
            throw new \LogicException('Soubor s obrázkem se nepodařilo načíst nebo je v nepodporovaném formátu');
        }
        $imageToDelete = new \AdminModule\Helpers\Image($oldImage->name, $oldImage->type, $this->config);
        $imageToDelete->delete();

        $imageName = $this->getUniqueImageName($uploadedFile->getSanitizedName());
        $newImage = new \AdminModule\Helpers\Image($imageName, $type, $this->config);
        $newImage->save($uploadedFile->getTemporaryFile());
        return $imageName;
    }

    /**
     * 
     * @param array $data
     * @return \Nette\Database\Table\ActiveRow
     * @throws \LogicException
     */
    private function getCurrentImage(array $data) {
        if (!isset($data['id_image'])) {
            throw new \LogicException('Není nastaveno id upravovaného obrázku');
        }
        if (($image = $this->get($data['id_image'])) === false) {
            throw new \LogicException('Obrázek se zadaným id neexistuje');
        }
        
        return $image;
    }

    /**
     * 
     * @param \AdminModule\Models\FileUpload $uploadedFile
     * @return boolean
     */
    private function checkFile($uploadedFile) {
        if (!$uploadedFile instanceof \Nette\Http\FileUpload) {
            return false;
        }
        if (!$uploadedFile->isOk()) {
            return false;
        }
        if (!$uploadedFile->isImage()) {
            return false;
        }
        return true;
    }

    /**
     * 
     * @param string $filePath
     * @return string
     */
    private function getUniqueImageName($filePath) {
        $fileNameParts = pathinfo($filePath);
        return $fileNameParts['filename'] . '_' . time() . '.' . $fileNameParts['extension'];
    }

}
